import router, {
  resetRouter
} from './router'
import store from './store/'
import {
  Message,
  Loading
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getCookie,
  setCookie,
  delCookie,
  setSessionStorage,
  getSessionStorage,
  deleteSessionStorage
} from '@/utils/base'

NProgress.configure({
  showSpinner: false
})
const whiteList = ['/login', '/test', '/fonticon', '/register', '/resetpassword'];

// 在每个路由生效之前，先进行一些处理，请参考 vue-router官方文档-导航钩子
router.beforeEach(async(to, from, next) => {
  NProgress.start();
  const isLogin = getCookie('isLogin');
  console.log( 'islogin', isLogin );
  if ( isLogin ) {
    
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      
      let noRoles = store.state.user.roles;
      if ( noRoles == null ) {
        // 判断当前用户是否已拉取完user_info信息
        //参数暂时无效
        const roles = Math.random();
        const accessRoutes = await store.dispatch('user/generateRoutes', roles);
        resetRouter();
        router.addRoutes(accessRoutes);
        next({ ...to,
          replace: true
        });
        
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

/*注册一个全局守卫*/
router.beforeResolve((to, from, next) => {
  next();
})

/*全局后置钩子*/
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
